package servlet;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swimv2.entity.User;
import swimv2.session.ILoginRemote;
import utils.SeU;

/**
 * Servlet implementation class login
 */
public class login extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public login() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.process(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.process(request,response);
	}

	private void process(HttpServletRequest request,HttpServletResponse response) {
		try 
		{
			String u = request.getParameter( SeU.USERNAME_ATTRIBUTE );
			String p = request.getParameter( SeU.PASSWORD_ATTRIBUTE);
			
			Context ic = new InitialContext();
			ILoginRemote l = (ILoginRemote)ic.lookup("ILoginRemote");
			
			if(l.LoginUser(u, p))
			{
				request.getSession().setAttribute(SeU.LOGIN_BEAN_ATTRIBUTE, l);
				
				User user = l.getLoggedUser();
				request.getSession().setAttribute(SeU.USER_ATTRIBUTE, user);
			}
		} 
		catch (NamingException e) {
			e.printStackTrace();
		}
		catch (Exception e1) {
			e1.printStackTrace();
		}
		finally
		{
			
			try {
				response.sendRedirect(response.encodeURL("Home"));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	

}
